﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProDivingAdmin2salmon14
{
    public partial class AddDataForm : Form, IAddDataForm
    {
        private bool isNew = false;
        private bool isEdit = false;
        private string amountOfDives;
        private Contest shhh;

        public AddDataForm()
        {
            InitializeComponent();

            this.VisibleChanged += new EventHandler(OnFormVisible);

            this.DiverGridView.Columns.Add("DiverName", "Name");
            this.DiverGridView.Columns.Add("DiverPersonNo", "Person No: (YYMMDDXXXX)");
            this.DiverGridView.Columns.Add("DiverNationality", "Nationality");
            this.DiverGridView.Columns.Add("DiverID", "Diver ID");
            this.DiverGridView.RowHeadersVisible = false;
            this.DiverGridView.Columns["DiverName"].ReadOnly = true;
            this.DiverGridView.Columns["DiverName"].SortMode = DataGridViewColumnSortMode.NotSortable;
            this.DiverGridView.Columns["DiverPersonNo"].ReadOnly = true;
            this.DiverGridView.Columns["DiverPersonNo"].SortMode = DataGridViewColumnSortMode.NotSortable;
            this.DiverGridView.Columns["DiverNationality"].ReadOnly = true;
            this.DiverGridView.Columns["DiverNationality"].SortMode = DataGridViewColumnSortMode.NotSortable;
            this.DiverGridView.Columns["DiverID"].ReadOnly = true;
            this.DiverGridView.Columns["DiverID"].SortMode = DataGridViewColumnSortMode.NotSortable;
            this.DiverGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
            this.DiverGridView.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.DiverGridView.CellEndEdit += new DataGridViewCellEventHandler(OnDiverCellEnterd);
            this.DiverGridView.AllowUserToAddRows = false;
            this.DiverGridView.CellMouseClick += new DataGridViewCellMouseEventHandler(OnCheckDiver);

            this.DiveGridView.Columns.Add("DiveCode", "Dive code");
            this.DiveGridView.Columns.Add("DiveName", "Dive name");
            this.DiveGridView.RowHeadersVisible = false;
            this.DiveGridView.Columns["DiveCode"].ReadOnly = true;
            this.DiveGridView.Columns["DiveCode"].SortMode = DataGridViewColumnSortMode.NotSortable;
            this.DiveGridView.Columns["DiveName"].ReadOnly = true;
            this.DiveGridView.Columns["DiveName"].SortMode = DataGridViewColumnSortMode.NotSortable;
            this.DiveGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            this.DiveGridView.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.DiveGridView.CellEndEdit += new DataGridViewCellEventHandler(OnDiveCodeEntered);
            this.DiveGridView.AllowUserToAddRows = false;
        }

        private void OnFormVisible(object sender, EventArgs e)
        {
            if (this.Visible) 
            {
                if (EventGetNewDiverList != null) 
                {
                    DiverList diverList = EventGetNewDiverList();
                    if (diverList.Count > 0)
                    {
                        foreach (var diver in diverList)
                        {
                            this.DiverGridView.Rows.Add(new DataGridViewRow());
                            this.DiverGridView.Rows[this.DiverGridView.Rows.Count - 1].Cells["DiverName"].Value = diver.fullName;
                            this.DiverGridView.Rows[this.DiverGridView.Rows.Count - 1].Cells["DiverPersonNo"].Value = diver.Nr;
                            this.DiverGridView.Rows[this.DiverGridView.Rows.Count - 1].Cells["DiverNationality"].Value = diver.nationality;
                            this.DiverGridView.Rows[this.DiverGridView.Rows.Count - 1].Cells["DiverID"].Value = diver.ID;
                        }
                        if (EventGetAmountOfDives != null) 
                        {
                            this.amountOfDives = EventGetAmountOfDives().ToString();
                        }
                    }
                    else 
                    {
                        bool isNumber = false;
                        while (!isNumber)
                        {
                            this.amountOfDives = Microsoft.VisualBasic.Interaction.InputBox("Please eneter the amount of dives for each diver:", "Amount of dives.", "5 - 6", this.Location.X, this.Location.Y).Trim();
                            if (Regex.Matches(this.amountOfDives, @"[5-6]").Count > 0) 
                            {
                                isNumber = true;
                            }
                        }
                    }
                }
            }
        }

        private void OnCheckDiver(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                if (EventGetDiveListFromDiver != null)
                {
                    this.DiveGridView.Rows.Clear();
                    foreach (var dive in EventGetDiveListFromDiver(new Diver("", "", Int32.Parse(this.DiverGridView.CurrentRow.Cells["DiverID"].Value.ToString()), "", new List<Dive>())))
                    {
                        this.DiveGridView.Rows.Add(new DataGridViewRow());
                        this.DiveGridView.Rows[this.DiveGridView.Rows.Count - 1].Cells["DiveCode"].Value = dive.diveCode;
                        this.DiveGridView.Rows[this.DiveGridView.Rows.Count - 1].Cells["DiveName"].Value = EventGetDiveName(dive.diveCode);
                    }
                    if (this.DiveGridView.Rows.Count == Int32.Parse(this.amountOfDives))
                    {
                        this.AddDive.Enabled = false;
                    }
                    else 
                    {
                        this.AddDive.Enabled = true;
                    }
                }
            }
            catch (NullReferenceException) 
            {
                return;
            }
        }

        private void OnDiverCellEnterd(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (!this.isEdit)
                {
                    this.DiverGridView.CurrentRow.Cells[this.DiverGridView.CurrentCell.ColumnIndex].ReadOnly = true;
                    if (this.DiverGridView.CurrentCell.ColumnIndex + 1 <= 3)
                    {
                        if (this.DiverGridView.CurrentCell.ColumnIndex == 1)
                        {
                            if (Regex.Matches(this.DiverGridView.CurrentCell.Value.ToString(), @"[a-zA-Z]").Count > 0)
                            {
                                this.DiverGridView.CurrentRow.Cells[this.DiverGridView.CurrentCell.ColumnIndex].ReadOnly = false;
                                this.DiverGridView.CurrentCell.Selected = true;
                                this.DiverGridView.BeginEdit(true);
                                return;
                            }
                            else if (this.DiverGridView.CurrentCell.Value.ToString().Length > 10 || this.DiverGridView.CurrentCell.Value.ToString().Length < 10)
                            {
                                this.DiverGridView.CurrentRow.Cells[this.DiverGridView.CurrentCell.ColumnIndex].ReadOnly = false;
                                this.DiverGridView.CurrentCell.Selected = true;
                                this.DiverGridView.BeginEdit(true);
                                return;
                            }
                        }
                        try
                        {
                            this.DiverGridView.CurrentRow.Cells[this.DiverGridView.CurrentCell.ColumnIndex + 1].ReadOnly = false;
                            this.DiverGridView.CurrentRow.Cells[this.DiverGridView.CurrentCell.ColumnIndex + 1].Selected = true;
                            this.DiverGridView.BeginEdit(true);
                        }
                        catch (InvalidOperationException)
                        {
                            return;
                        }

                    }
                    else
                    {
                        if (EventAddDiverToList != null && !this.isEdit)
                        {
                            EventAddDiverToList(new Diver(this.DiverGridView.CurrentRow.Cells["DiverName"].Value.ToString(), this.DiverGridView.CurrentRow.Cells["DiverPersonNo"].Value.ToString(), Int32.Parse(this.DiverGridView.CurrentRow.Cells["DiverID"].Value.ToString()), this.DiverGridView.CurrentRow.Cells["DiverNationality"].Value.ToString(), new List<Dive>()));
                        }
                    }
                }
                else if (EventEditDiver != null && EventGetDiveListFromDiver != null && this.isEdit)
                {
                    try
                    {
                        if (this.DiverGridView.CurrentCell.Value.ToString() != "")
                        {
                            var diverList = EventGetDiveListFromDiver(new Diver("", "", Int32.Parse(this.DiverGridView.CurrentRow.Cells["DiverID"].Value.ToString()), "", new List<Dive>()));
                            EventEditDiver(this.DiverGridView.CurrentRow.Index, new Diver(this.DiverGridView.CurrentRow.Cells["DiverName"].Value.ToString(), this.DiverGridView.CurrentRow.Cells["DiverPersonNo"].Value.ToString(), Int32.Parse(this.DiverGridView.CurrentRow.Cells["DiverID"].Value.ToString()), this.DiverGridView.CurrentRow.Cells["DiverNationality"].Value.ToString(), diverList));
                            this.isEdit = false;
                        }
                    }
                    catch(ArgumentOutOfRangeException)
                    {
                        if(EventDeleteDiver != null && EventAddDiverToList != null)
                        {
                            EventAddDiverToList(new Diver(this.DiverGridView.CurrentRow.Cells["DiverName"].Value.ToString(), this.DiverGridView.CurrentRow.Cells["DiverPersonNo"].Value.ToString(), Int32.Parse(this.DiverGridView.CurrentRow.Cells["DiverID"].Value.ToString()), this.DiverGridView.CurrentRow.Cells["DiverNationality"].Value.ToString(), new List<Dive>()));
                        }   
                    }
                }
            }
            catch (NullReferenceException) 
            {
                return;
            }
        }

        private void OnDiveCodeEntered(object sender, DataGridViewCellEventArgs e)
        {
            if (this.isNew)
            {
                if (EventGetDiveName != null)
                {
                    this.DiveGridView.CurrentRow.Cells["DiveName"].Value = EventGetDiveName(this.DiveGridView.CurrentCell.Value.ToString().ToUpper());
                }

                this.isNew = false;
                this.DiveGridView.CurrentRow.Cells["DiveCode"].Value = this.DiveGridView.CurrentRow.Cells["DiveCode"].Value.ToString().ToUpper();
                this.DiveGridView.CurrentCell.ReadOnly = true;

                if (EventAddDiveToDiver != null) 
                {
                    EventAddDiveToDiver(new Diver("","", Int32.Parse(this.DiverGridView.CurrentRow.Cells["DiverID"].Value.ToString()),"",new List<Dive>()), new Dive(this.DiveGridView.CurrentRow.Cells["DiveCode"].Value.ToString()));
                }
                if (this.DiveGridView.Rows.Count == Int32.Parse(this.amountOfDives)) 
                {
                    this.AddDive.Enabled = false;
                }
            }
            else if (this.isEdit) 
            {
                if (EventGetDiveName != null) 
                {
                    this.DiveGridView.CurrentRow.Cells["DiveName"].Value = EventGetDiveName(this.DiveGridView.CurrentCell.Value.ToString().ToUpper());
                }

                this.isEdit = false;
                this.DiveGridView.CurrentRow.Cells["DiveCode"].Value = this.DiveGridView.CurrentRow.Cells["DiveCode"].Value.ToString().ToUpper();
                this.DiveGridView.CurrentCell.ReadOnly = true;

                if (EventEditDiveToDiver != null) 
                {
                    EventEditDiveToDiver(new Diver("", "", Int32.Parse(this.DiverGridView.CurrentRow.Cells["DiverID"].Value.ToString()), "", new List<Dive>()), new Dive(this.DiveGridView.CurrentRow.Cells["DiveCode"].Value.ToString()), this.DiveGridView.CurrentRow.Index);
                }
            }
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog diverListFilePath = new OpenFileDialog();

            diverListFilePath.Filter = "Diver Files (.di)|*.di";
            diverListFilePath.FilterIndex = 0;

            diverListFilePath.Multiselect = false;

            DialogResult result = diverListFilePath.ShowDialog(this);
            if (result == System.Windows.Forms.DialogResult.OK) 
            {
                if (EventLoadDiverList != null) 
                {
                    foreach (var diver in EventLoadDiverList(diverListFilePath.FileName))
                    {
                        this.DiverGridView.Rows.Add(new DataGridViewRow());
                        this.DiverGridView.Rows[this.DiverGridView.Rows.Count - 1].Cells["DiverName"].Value = diver.fullName;
                        this.DiverGridView.Rows[this.DiverGridView.Rows.Count - 1].Cells["DiverPersonNo"].Value = diver.Nr;
                        this.DiverGridView.Rows[this.DiverGridView.Rows.Count - 1].Cells["DiverNationality"].Value = diver.nationality;
                        this.DiverGridView.Rows[this.DiverGridView.Rows.Count - 1].Cells["DiverID"].Value = diver.ID;
                    }
                }
            }
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string toFewDives = "";
            if (EventGetNewDiverList != null)
            {
                foreach (var diver in EventGetNewDiverList())
                {
                    if (diver.diveList.Count < Int32.Parse(this.amountOfDives))
                    {
                        toFewDives = toFewDives.Insert(toFewDives.Length, ", " + diver.fullName);
                    }
                }
                if (toFewDives != "")
                {
                    toFewDives = toFewDives.Remove(0, 1);
                }
            }

            if (toFewDives == "")
            {
                SaveFileDialog filePath = new SaveFileDialog();

                filePath.Filter = "Diver Files (*.di)|*.di";

                DialogResult result = filePath.ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    if (EventGetNewDiverList != null && EventSaveDivers != null)
                    {
                        EventSaveDivers(EventGetNewDiverList(), filePath.FileName);
                    }
                }
            }
            else 
            {
                MessageBox.Show(this, "To few dives on:" + Environment.NewLine + toFewDives, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AddDiver_Click(object sender, EventArgs e)
        {
            this.DiverGridView.Rows.Add(new DataGridViewRow());
            this.DiverGridView.Rows[this.DiverGridView.Rows.Count - 1].Cells["DiverName"].Selected = true;
            this.DiverGridView.Rows[this.DiverGridView.Rows.Count - 1].Cells["DiverName"].ReadOnly = false;
            this.DiverGridView.BeginEdit(true);
        }

        private void DeleteDiver_Click(object sender, EventArgs e)
        {
            try
            {
                this.DiverGridView.Rows.Remove(this.DiverGridView.CurrentRow);
                if (EventDeleteDiver != null) 
                {
                    EventDeleteDiver(this.DiverGridView.CurrentRow.Index);
                }
            }
            catch (NullReferenceException) 
            {
                System.Console.WriteLine("Can't delete something that doesn't exist!");
            }
        }

        private void EditDiver_Click(object sender, EventArgs e)
        {
            try
            {
                this.DiverGridView.CurrentCell.ReadOnly = false;
                this.DiverGridView.BeginEdit(true);
                this.isEdit = true;
            }
            catch (NullReferenceException) 
            {
                System.Console.WriteLine("Can't edit something that doesn't exist!");
            }
        }

        private void AddDive_Click(object sender, EventArgs e)
        {
            this.DiveGridView.Rows.Add(new DataGridViewRow());
            this.DiveGridView.Rows[this.DiveGridView.Rows.Count - 1].Cells["DiveCode"].Selected = true;
            this.DiveGridView.Rows[this.DiveGridView.Rows.Count - 1].Cells["DiveCode"].ReadOnly = false;
            this.DiveGridView.BeginEdit(true);
            this.isNew = true;
        }

        private void DeleteDive_Click(object sender, EventArgs e)
        {
            try
            {
                if (EventDeleteDiveFromDiver != null)
                {
                    EventDeleteDiveFromDiver(new Diver("", "", Int32.Parse(this.DiverGridView.CurrentRow.Cells["DiverID"].Value.ToString()), "", new List<Dive>()), this.DiveGridView.CurrentRow.Index);
                    this.DiveGridView.Rows.Remove(this.DiveGridView.CurrentRow);
                    AddDive.Enabled = true;
                }
            }
            catch (ArgumentNullException) 
            {
                System.Console.WriteLine("Can't delete something that doesn't exist!");
            }
        }

        private void EditDive_Click(object sender, EventArgs e)
        {
            try
            {
                this.DiveGridView.CurrentRow.Cells["DiveCode"].ReadOnly = false;
                this.DiveGridView.BeginEdit(true);
                this.isEdit = true;
            }
            catch (NullReferenceException) 
            {
                System.Console.WriteLine("Can't edit something that doesn't exist!");
            }
        }

        public event DelegateAddDiverToList EventAddDiverToList = null;

        public event DelegateAddDiveToDiver EventAddDiveToDiver = null;

        public event DelegateGetDiveListFromDiver EventGetDiveListFromDiver = null;

        public event DelegateGetDiveName EventGetDiveName = null;

        public event DelegateDeleteDiveFromDiver EventDeleteDiveFromDiver = null;

        public event DelegateGetNewDiverList EventGetNewDiverList = null;

        public event DelegateSaveDivers EventSaveDivers = null;

        public event DelegateEditDiveToDiver EventEditDiveToDiver = null;

        public event DelegateEditDiver EventEditDiver = null;

        public event DelegateDeleteDiver EventDeleteDiver = null;

        public event DelegateGetAmountOfDives EventGetAmountOfDives = null;

        public event DelegateLoadDiverList EventLoadDiverList = null;
    }
}